package com.deyun.panelcabinet;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.FaceDetector;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.bifan.detectlib.FaceDetectTextureView;
import com.bifan.detectlib.FaceDetectView;
import com.deyun.panelcabinet.activity.RegisterActivity;
import com.deyun.panelcabinet.adapter.TestAdapter;
import com.deyun.panelcabinet.entity.FaceEntity;
import com.deyun.panelcabinet.entity.TestEntity;
import com.deyun.panelcabinet.utils.MyStringUtils;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import androidx.core.content.ContextCompat;
import androidx.core.content.PermissionChecker;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.f1reking.serialportlib.SerialPortHelper;
import me.f1reking.serialportlib.listener.ISerialPortDataListener;

public class MainActivity extends Activity {

    public SerialPortHelper serialPortHelper;
    public Gson gson = new Gson();
    public CustomPopWindow cabinetPopWindow;

    @BindView(R.id.faceDetectView)
    FaceDetectView faceDetectView;
    @BindView(R.id.rl_main)
    RelativeLayout rl_main;
    @BindView(R.id.rl_user)
    RelativeLayout rl_user;
    @BindView(R.id.lv_user_info)
    ListView lv_user_info;
    @BindView(R.id.tv_select_all)
    TextView tv_select_all;
    @BindView(R.id.et_search)
    EditText et_search;


    // 判断是开锁还是上锁的标示
    public boolean isOpenOrLock = true;
    // 拼装完成的字符串关锁时获取
    public String str_lock_state = null;
    // 拼装完成的字符串开锁时获取
    public String str_open_state = null;
    // 用户是存东西还是取东西的标识
    public Boolean isGetOrSave = false;

    // 测试相关
    public TestAdapter testAdapter;
    public ArrayList<TestEntity> al;
    public ArrayList<TestEntity> al_search_result;
    public boolean isSelectAll = true;

    private LoadingDialog ld;




    public void showLoading(String loadingMessage) {
        ld = new LoadingDialog(this);
        if (loadingMessage.equals("")) {
            ld.setLoadingText("努力加载中...")
                    .show();
        } else {
            ld.setLoadingText(loadingMessage)
                    .show();
        }
    }

    public void closeLoading() {
        if (ld != null) {
            ld.close();
        }
    }

    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private boolean isSavingPic = false;
    // 防止重复提交图片到服务器和持续保存人脸图片到本地
    private boolean isSubmitToServer = false;
    // 人脸通过后会缓存上一次的图片取消标识
    private boolean b_temp = false;


    @OnClick({R.id.tv_get, R.id.tv_save, R.id.tv_manager, R.id.tv_test, R.id.tv_user_show, R.id.tv_close_user, R.id.tv_select_all, R.id.tv_commit, R.id.tv_search_confirm, R.id.tv_close_faceRecognition})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.tv_get:
                isGetOrSave = true;
                if (checkPermission()) {
                    cleanPic();
                    b_temp = false;
                    initFaceRecognitionParams();
                } else {
                    Toast.makeText(getApplicationContext(), "没有权限", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_save:
                isGetOrSave = false;
                if (checkPermission()) {
                    cleanPic();
                    b_temp = false;
                    initFaceRecognitionParams();
                } else {
                    Toast.makeText(getApplicationContext(), "没有权限", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_manager:
                if (faceDetectView.isHasInit()) {
                    faceDetectView.stopCameraPreview();
                    faceDetectView.getFaceRectView().clearBorder();
                    faceDetectView.setVisibility(View.INVISIBLE);
                }
                showLoginPop();

                break;
            case R.id.tv_test:
                showPop();
                break;
            case R.id.tv_user_show:
                rl_user.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_close_user:
                rl_user.setVisibility(View.INVISIBLE);
                hideSystemNavigationBar();
                break;
            case R.id.tv_commit:
                rl_user.setVisibility(View.INVISIBLE);
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < al.size(); i++) {
                    TestEntity testEntity = al.get(i);
                    if (testEntity.isException()) {
                        sb.append(testEntity.toString());
                    }
                }
                LogUtils.d("异常人员数据:" + sb);
                hideSystemNavigationBar();
//                showLoading("数据提交中。。。");
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        closeLoading();
//                        Toast.makeText(getApplicationContext(), "数据已提交", Toast.LENGTH_SHORT).show();
//                    }
//                }, 1000);

                break;
            case R.id.tv_select_all:
                for (int i = 0; i < al.size(); i++) {
                    if (isSelectAll) {
                        al.get(i).setCheck(true);
                        tv_select_all.setText("反选");
                    } else {
                        al.get(i).setCheck(false);
                        tv_select_all.setText("全选");
                    }
                }
                isSelectAll = !isSelectAll;
                testAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_search_confirm:
                // 恢复到默认人员列表显示，隐藏软键盘
                et_search.setText("");
                hideKeyboard(this);
                hideSystemNavigationBar();
                break;
            case R.id.tv_close_faceRecognition:
                if (faceDetectView.isHasInit()) {
                    faceDetectView.stopCameraPreview();
                    faceDetectView.getFaceRectView().clearBorder();
                    faceDetectView.setVisibility(View.INVISIBLE);
                }
                break;
        }
    }

    // 清除图片
    public void cleanPic() {
        String picPath = Environment.getExternalStorageDirectory() + "/face.jpg";
        File facePicFile = new File(picPath);
        if (facePicFile.exists()) {
            facePicFile.delete();
        }
        LogUtils.d("删除图片");
    }


    // 隐藏软键盘
    public void hideKeyboard(Activity context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(context.getWindow().getDecorView().getWindowToken(), 0);
    }


    // 隐藏底部和顶部状态栏
    private void hideSystemNavigationBar() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View view = this.getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    private class SavePicRunnable implements Runnable {
        Bitmap bitmap;

        SavePicRunnable(Bitmap bitmap) {
            this.bitmap = bitmap;
        }

        @Override
        public void run() {
            isSavingPic = false;
            if (b_temp) {
                saveFacePicToLocal(bitmap);
            }
            b_temp = true;

        }
    }

    // 保存人脸图片到本地
    private void saveFacePicToLocal(Bitmap bitmap) {
        LogUtils.d("检测到人脸，图片正在保存到本地");
        // 安卓10的适配 沙盒模式
        if (android.os.Build.VERSION.SDK_INT >= 30) {
            try {
                // 沙盒下的目录名
                String signImage = "temp";
                // 沙盒下的图片名
                String fileName = "face.jpg";
                File PICTURES = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                // 沙盒下的目录
                File imageFileDirectory = new File(PICTURES + "/" + signImage);
                if (imageFileDirectory.exists()) {
                    File imageFile = new File(PICTURES + "/" + signImage + "/" + fileName);
                    FileOutputStream fileOutputStream = new FileOutputStream(imageFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    bitmap.recycle();
                } else if (imageFileDirectory.mkdir()) {//如果该文件夹不存在，则新建
                    File imageFile = new File(PICTURES + "/" + signImage + "/" + fileName);
                    FileOutputStream fileOutputStream = new FileOutputStream(imageFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    bitmap.recycle();
                    upLoadImage(imageFile);
                }
            } catch (Exception e) {
                LogUtils.d("安卓10保存图片失败信息 " + e.toString());
            }
        } else {
            String picPath = Environment.getExternalStorageDirectory() + "/face.jpg";
            FileOutputStream fileOutputStream = null;
            File facePicFile = new File(picPath);
            try {
                facePicFile.createNewFile();
            } catch (IOException e) {
                LogUtils.d("保存失败" + e.toString() + "," + picPath);
                e.printStackTrace();
            }
            try {
                fileOutputStream = new FileOutputStream(facePicFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if (fileOutputStream != null) {
                BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                try {
                    bos.flush();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            bitmap.recycle();
            upLoadImage(facePicFile);
        }
    }

    // 显示开关柜子弹出框
    public void showPop() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_select_cabinet, null);

        cabinetPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)//显示的布局，还可以通过设置一个View
                .size(600, 400) //设置显示的大小，不设置就默认包裹内容
                .setFocusable(false)//是否获取焦点，默认为ture
                .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setClippingEnable(false)
                .setBgDarkAlpha(0.7f) // 控制亮度
                .create()//创建PopupWindow
                .showAtLocation(rl_main, Gravity.CENTER, 0, 0);//显示PopupWindow

        TextView tv_A = contentView.findViewById(R.id.tv_A);
        tv_A.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setSerialPortOrder(1);
            }
        });

        TextView tv_B = contentView.findViewById(R.id.tv_B);
        tv_B.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setSerialPortOrder(2);
            }
        });

        TextView tv_C = contentView.findViewById(R.id.tv_C);
        tv_C.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setSerialPortOrder(3);
            }
        });

    }

    // 显示管理员登录的popwindow
    public void showLoginPop() {
        Resources resources = getResources();
        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        int widthPixels = (int) (displayMetrics.widthPixels * 0.8);//当前屏幕宽
        int heightPixels = (int) (displayMetrics.heightPixels * 0.4);//当前屏幕高
        View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_login, null);
        final CustomPopWindow customPopWindow = new CustomPopWindow.PopupWindowBuilder(MainActivity.this)
                .setView(contentView)
                .setFocusable(true)
                .setOutsideTouchable(false)//是否PopupWindow 以外触摸dissmiss
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        hideSystemNavigationBar();
                    }
                })
                .setBgDarkAlpha(0.7f) // 控制亮度
                .size(widthPixels, heightPixels)//显示大小
                .create()
                .showAtLocation(rl_main, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 300);

        final EditText et_username = contentView.findViewById(R.id.et_username);
        final EditText et_password = contentView.findViewById(R.id.et_password);
        final ImageView iv_delete_username = contentView.findViewById(R.id.iv_username_delete);
        final ImageView iv_delete_password = contentView.findViewById(R.id.iv_password_delete);

        iv_delete_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_password.setText("");
            }
        });

        iv_delete_username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_username.setText("");
            }
        });

        et_username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().trim().equals("")) {
                    iv_delete_username.setVisibility(View.INVISIBLE);
                } else {
                    iv_delete_username.setVisibility(View.VISIBLE);
                }
            }
        });

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().trim().equals("")) {
                    iv_delete_password.setVisibility(View.INVISIBLE);
                } else {
                    iv_delete_password.setVisibility(View.VISIBLE);
                }
            }
        });


        Button btn_login = contentView.findViewById(R.id.btn_login);
        Button btn_cancel = contentView.findViewById(R.id.btn_cancel);
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideSoftKeyboard(MainActivity.this, view);
                if (et_username.getText().toString().trim().equals("admin") && et_password.getText().toString().trim().equals("123456")) {
                    // 处理登录逻辑
                    customPopWindow.dissmiss();
                    Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                    cleanPic();
                    Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), "账号或者密码错误", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideSystemNavigationBar();
                customPopWindow.dissmiss();
            }
        });
    }

    // 获取焦点弹出软键盘
    public void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //这里给它设置了弹出的时间，
        imm.toggleSoftInput(50, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //view为接受软键盘输入的视图，SHOW_FORCED表示强制显示
    public static void hideSoftKeyboard(Activity activity, View view) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }


    public void setSerialPortOrder(final int type) {
        if (serialPortHelper == null) {
            serialPortHelper = new SerialPortHelper();
            // 串口地址
            serialPortHelper.setPort("/dev/ttyS4");
            // 波特率
            serialPortHelper.setBaudRate(9600);
            // 停止位
            serialPortHelper.setStopBits(1);
        }
        // 打开串口
        if (!serialPortHelper.isOpen()) {
            serialPortHelper.open();
            LogUtils.d("串口打开成功");
            serialPortHelper.setISerialPortDataListener(new ISerialPortDataListener() {
                @Override
                public void onDataReceived(byte[] bytes) {
                    String str = MyStringUtils.byteToArray(bytes);
                    if (isOpenOrLock) {
                        LogUtils.d("关闭锁的返回数据 = " + str);
                        // 锁状态解析结果赋值
                        str_lock_state = MyStringUtils.ParseLockReturnInfo(str);
                        LogUtils.d("str_lock_state = " + str_lock_state);
                        int lockNumber = MyStringUtils.comparisonGetNumberLock(str_open_state, str_lock_state);
                        if (lockNumber != -1) {
                            lockNumber++;
                            final int a = lockNumber;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    if (!isGetOrSave) {
                                        rl_user.setVisibility(View.VISIBLE);
                                    }

                                    if (cabinetPopWindow != null) {
                                        cabinetPopWindow.dissmiss();
                                    }
                                    Toast.makeText(getApplicationContext(), "第" + a + "柜门完成上锁", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        str_open_state = MyStringUtils.ParseLockReturnInfo(str);
                    } else {
                        LogUtils.d("开锁的返回数据 = " + str);
                        str_open_state = MyStringUtils.ParseLockReturnInfo(str);
                        LogUtils.d("str_open_state = " + str_open_state);
                        isOpenOrLock = !isOpenOrLock;
                    }
                }

                @Override
                public void onDataSend(byte[] bytes) {
                    LogUtils.d("发送的数据 = " + MyStringUtils.byteToArray(bytes));
                }
            });
        }
        // 用户点击开锁的标识
        isOpenOrLock = !isOpenOrLock;
        switch (type) {
            case 1:
                serialPortHelper.sendHex("01050000FF008C3A");
                Toast.makeText(getApplicationContext(), "柜门A已经打开，取出用品后记得关闭", Toast.LENGTH_SHORT).show();
                break;
            case 2:
                serialPortHelper.sendHex("01050001FF00DDFA");
                Toast.makeText(getApplicationContext(), "柜门B已经打开，取出用品后记得关闭", Toast.LENGTH_SHORT).show();
                break;
            case 3:
                serialPortHelper.sendHex("01050002FF002DFA");
                Toast.makeText(getApplicationContext(), "柜门C已经打开，取出用品后记得关闭", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serialPortHelper != null) {
            serialPortHelper.close();
        }
        if (faceDetectView != null) {
            faceDetectView.release();
        }
    }

    // 屏蔽home和返回
    public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000;

    @Override
    public void onAttachedToWindow() {
        this.getWindow().addFlags(FLAG_HOMEKEY_DISPATCHED);
        super.onAttachedToWindow();
    }

    @Override
    public void onBackPressed() {
        // super.onBackPressed();
    }

    // 初始化人脸识别并开始启用
    public void initFaceRecognitionParams() {
        LogUtils.d("初始化人脸识别");
        faceDetectView.setVisibility(View.VISIBLE);
        if (!faceDetectView.isHasInit()) {
            //必须是在view可见后进行初始化
            faceDetectView.initView();
            faceDetectView.initCamera();
            faceDetectView.getDetectConfig().CameraType = Camera.CameraInfo.CAMERA_FACING_FRONT;
            faceDetectView.getDetectConfig().EnableFaceDetect = true;
            faceDetectView.getDetectConfig().MinDetectTime = 2000;
            faceDetectView.getDetectConfig().Simple = 0.5f;//图片检测时的压缩取样率，0~1，越小检测越流畅
            faceDetectView.getDetectConfig().MaxDetectTime = 5000;//进入智能休眠检测，以2秒一次的这个速度检测
            faceDetectView.getDetectConfig().EnableIdleSleepOption = false;//不启用智能休眠检测机制
            faceDetectView.getDetectConfig().IdleSleepOptionJudgeTime = 1000 * 10;//1分钟内没有检测到人脸，进入智能休眠检测
        }
        faceDetectView.startCameraPreview();
    }


    // 上传图片到服务器进行比对
    public void upLoadImage(File file) {
        if (file != null && isSubmitToServer == false) {
            isSubmitToServer = true;
            String url_test = "http://10.1.20.95:9000/search_face/";
            RequestParams params = new RequestParams(url_test);
            params.setCacheMaxAge(0);
            params.setMultipart(true);
            params.addBodyParameter("file", file, "multipart/form-data");
            LogUtils.d("upload_url = " + params.getUri());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    isSubmitToServer = false;
                    LogUtils.d("result = " + result);
                    try {
                        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
                        FaceEntity faceEntity = gson.fromJson(result, FaceEntity.class);
                        boolean face_found = (boolean) jsonObject.get("face_found");
                        String msg = (String) jsonObject.get("msg");
                        if (faceEntity.getUser() != null && face_found) {
                            // Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
                            Toast.makeText(getApplicationContext(), "姓名：" + faceEntity.getUser().getUser_name() + " 已识别", Toast.LENGTH_SHORT).show();

                            if (faceDetectView.isHasInit()) {
                                faceDetectView.stopCameraPreview();
                                faceDetectView.getFaceRectView().clearBorder();
                                faceDetectView.setVisibility(View.INVISIBLE);
                                // 显示快递柜可代开页面
                                showPop();
                            }

                        } else if (faceEntity.getUser() == null && msg != null) {
                            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    isSubmitToServer = false;
                    LogUtils.d("onError = " + ex.getMessage());
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // 测试相关
        al = new ArrayList<>();
        al_search_result = new ArrayList<>();

        for (int i = 0; i < 160; i++) {
            TestEntity testEntity = new TestEntity(i, false, "张三" + i, false);
            al.add(testEntity);
        }

        testAdapter = new TestAdapter(al, this);
        lv_user_info.setAdapter(testAdapter);

        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                LogUtils.d("str = " + charSequence.toString());
                if (charSequence.toString().trim().equals("")) {
                    testAdapter = new TestAdapter(al, MainActivity.this);
                } else {
                    // 开始进行搜索
                    al_search_result.clear();
                    String str_search = charSequence.toString().trim();
                    for (int j = 0; j < al.size(); j++) {
                        if (al.get(j).getName().contains(str_search)) {
                            al_search_result.add(al.get(j));

                        }
                    }
                    testAdapter = new TestAdapter(al_search_result, MainActivity.this);
                }
                testAdapter.notifyDataSetChanged();
                lv_user_info.setAdapter(testAdapter);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        faceDetectView.setFramePreViewListener(new FaceDetectTextureView.IFramePreViewListener() {
            @Override
            public boolean onFrame(Bitmap preFrame) {
                //每一帧回调
                //这个这帧preFrame处理了就是进行了回收，返回true
                //否则返回false，内部进行回收处理
                return false;
            }

            @Override
            public boolean onFaceFrame(Bitmap preFrame, FaceDetector.Face[] faces) {
                //faces是检测出来的人脸参数
                //检测到人脸的回调,保存人脸图片到本地
                if (isSavingPic == false && isSubmitToServer == false) {
                    isSavingPic = true;
                    executorService.submit(new SavePicRunnable(preFrame));
//                    if (faces.length != 0) {
//                        LogUtils.d("是否可信参数" + faces[0].confidence());
//                        LogUtils.d("双眼距离" + faces[0].eyesDistance());
//                    }
                }
                //这个这帧preFrame处理了就是进行了回收，返回true
                //否则返回false，内部进行回收处理
                return true;
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();
        hideSystemNavigationBar();
        if (checkPermission()) {

        } else {
            initPermission();
        }
    }

    // 检测权限
    public boolean checkPermission() {
        if (android.os.Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PermissionChecker.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED) {
            return false;
        } else {
            return true;
        }
    }

    // 申请权限
    public void initPermission() {
        // 申请权限。
        AndPermission.with(this)
                .permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE).onGranted(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                LogUtils.d("点击了同意");
            }
        }).onDenied(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                if (checkPermission()) {
                    LogUtils.d("点击了拒绝同意");
                } else {
                    Toast.makeText(getApplicationContext(), "权限被禁止，人脸识别功能无法使用", Toast.LENGTH_SHORT).show();
                }
            }
        }).start();
    }
}